<!-- 检测项目 -->
<div class="open-form">
  <div class="open-model">
    <div class="open-auto">
      <!-- 头部操作栏 -->
      <div class="layui-form toolbar">
        <div class="layui-form-item">
          <div class="layui-inline" name="inputName">
            <label class="layui-form-label w-auto">名称：</label>
            <div class="layui-input-inline mr0">
              <input name="name" class="layui-input" type="text" placeholder="请输入名称" />
            </div>
          </div>
          <div class="layui-inline">
            <button class="layui-btn icon-btn" id="searchBtn" lay-filter="itemTableFormSubSearchLog" lay-submit layui-form-keyDownSearch="true">
              <i class="layui-icon">&#xe615;</i>搜索
            </button>
            <button id="productItemBtnAdd" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加检测项目</button>
            <button id="productItemCategoryBtnAdd" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>检测项目分类</button>
            <button id="checkListBtn" class="layui-btn icon-btn" style="background: #ff5722; display: none">确认选择</button>
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <table class="layui-table" id="productItemTable" lay-filter="productItemTable"></table>
    </div>
    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
    </div>
  </div>
</div>

<script type="text/html" id="productItemTableBar">
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="editItem">修改</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="productItemForm">
  <form lay-filter="productItemForm" class="layui-form model-form" style="padding-top: 20px;">
    <input name="id" type="hidden" />
    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">物资分类</label>
        <div class="layui-input-block">
          <select id="productType" name="productType" lay-filter="productType" disabled></select>
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">物资性质</label>
        <div class="layui-input-block">
          <select id="productNature" name="productNature" lay-filter="productNature" disabled></select>
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">检测类型</label>
        <div class="layui-input-block">
          <select id="itemType" name="itemType" lay-filter="itemType"></select>
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">检测项目分类</label>
        <div class="layui-input-block">
          <select id="itemCategoryId" name="itemCategoryId" lay-filter="itemCategoryId" required lay-verify="required"></select>
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">检测业务类型</label>
        <div class="layui-input-block">
          <select id="qualityTestingTypeId" name="qualityTestingTypeId" lay-filter="qualityTestingTypeId" required lay-verify="required"></select>
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">检测业务分类</label>
        <div class="layui-input-block">
          <select id="qualityTestingCategoryId" name="qualityTestingCategoryId" lay-filter="qualityTestingCategoryId" required lay-verify="required"></select>
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">检测项目代码</label>
        <div class="layui-input-block">
          <input name="code" placeholder="请输入检测项目代码" type="text" class="layui-input" lay-verify="required" required />
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">检测项目名称</label>
        <div class="layui-input-block">
          <input name="name" placeholder="请输入检测项目名称" type="text" class="layui-input" lay-verify="required" required />
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">检测方法</label>
        <div class="layui-input-block">
          <select id="testMethod" name="testMethod" lay-filter="testMethod"></select>
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">检测器具</label>
        <div class="layui-input-block">
          <input name="testTool" placeholder="请输入检测器具" type="text" class="layui-input" lay-verify="required" required />
        </div>
      </div>
    </div>

    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">样式</label>
        <div class="layui-input-block">
          <select id="style" name="style" lay-filter="style"></select>
        </div>
      </div>
    </div>
    <div class="layui-col-xs6">
      <div class="layui-form-item">
        <label class="layui-form-label">排序</label>
        <div class="layui-input-block">
          <input name="sort" placeholder="请输入排序" type="text" class="layui-input" lay-verify="" required />
        </div>
      </div>
    </div>

    <div class="layui-col-xs12">
      <div class="layui-form-item">
        <label class="layui-form-label">描述</label>
        <div class="layui-input-block">
          <textarea name="remark" placeholder="请输入描述" class="layui-textarea" />
        </div>
      </div>
    </div>

    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
      <button class="layui-btn" lay-filter="productItemFormSubmit" lay-submit>保存</button>
    </div>
  </form>
</script>

<script type="text/html" id="productItemCategoryForm">
  <form lay-filter="productItemCategoryForm" class="layui-form model-form">
    <input name="id" type="hidden" />
    <div class="layui-form-item">
      <label class="layui-form-label">物资分类</label>
      <input name="productType" type="hidden" />
      <div class="layui-input-inline mr0" id="selectProductTypeQuery" style="width: 377px;" disabled></div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">物资性质</label>
      <div class="layui-input-block">
        <select id="productNature" name="productNature" disabled></select>
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">检测类型</label>
      <div class="layui-input-block">
        <select id="itemType" name="itemType" lay-search lay-verify="required"></select>
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">编码</label>
      <div class="layui-input-block">
        <input name="code" placeholder="请输入编码" type="text" class="layui-input" lay-verify="required" required />
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">名称</label>
      <div class="layui-input-block">
        <input name="name" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required" required />
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">排序</label>
      <div class="layui-input-block">
        <input name="sort" placeholder="请输入排序" type="text" class="layui-input" lay-verify="number" required />
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">备注</label>
      <div class="layui-input-block">
        <textarea id="remark" name="remark" placeholder="请输入备注" class="layui-textarea" />
      </div>
    </div>

    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
      <button class="layui-btn" lay-filter="productItemCategoryFormSubmit" lay-submit>保存</button>
    </div>
  </form>
</script>

<!-- js部分 -->
<script>
  layui.use(["layer", "form", "table", "laydate", "admin", "laytpl", "tableTreeDj", "config"], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var laydate = layui.laydate;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    var laytpl = layui.laytpl;
    var tableTree = layui.tableTreeDj;
    // 回显计量单位数据

    var data = admin.getTempData("data") || {};
    console.log("data", data);
    if (parentData.productTypeId) {
      
      data.id = parentData.productTypeId;
      $("#checkListBtn").show();
      $("#searchBtn").hide();
      $('[name="inputName"]').hide();
      $("#checkListBtn").click(() => {
        var checkStatus = table.checkStatus("productItemTable"); // 'demo'是表格的ID
        var data = checkStatus.data; // 选中的数据
        if (typeof parent.layui !== "undefined") {
          window.childData.list = data;
          console.log(123, window.childData.list);
          layer.close(parentData.zindex); // 关闭指定的弹窗
        }
      });
    } else {
      if (parentData && parentData.data && parentData.data.id) {
        data.id = parentData.data.id;
      }
      $("#checkListBtn").hide();
      $("#searchBtn").show();
      $('[name="inputName"]').show();
    }
    console.log(1112, parentData);
    // 渲染表格
    var insTb = table.render({
      elem: "#productItemTable",
      url: config.base + "enterprise/product/admin/productItem/list?productType=" + data.id,
      page: parentData.productTypeId ? false : true,
      limit: parentData.productTypeId ? 99999 : 10,
      cellMinWidth: 100,
      cols: [
        [
          { type: "checkbox", fixed: "left" },
          { type: "numbers", title: "序号" },
          { field: "name", align: "center", title: "检测项目名称" },
          { field: "code", align: "center", title: "检测项目编码" },
          { field: "itemCategoryName", align: "center", title: "检测项目分类" },
          { field: "itemTypeName", align: "center", title: "检测类型" },
          { field: "productTypeName", align: "center", title: "物资分类" },
          { field: "productNatureName", align: "center", title: "物资性质" },
          { field: "qualityTestingTypeName", align: "center", title: "检测业务类型" },
          { field: "qualityTestingCategoryName", align: "center", title: "检测业务分类" },
          { field: "testMethodName", align: "center", title: "检测方法" },
          { field: "testTool", align: "center", title: "检测器具" },
          { field: "createTime", align: "center", title: "创建时间", width: 160 },
          { align: "center", toolbar: "#productItemTableBar", title: "操作", width: 160 }
        ]
      ],
      done: function (res, curr, count) {
        // // 遍历 newList 和表格数据
        if (parentData.checkList && parentData.checkList.length > 0) {
          table.cache["productItemTable"].forEach((item, index) => {
            const isSelected = parentData.checkList.some((checkItem) => checkItem.id === item.id);
            if (isSelected) {
              item["LAY_CHECKED"] = true;
              $('div.layui-table-fixed input[name="layTableCheckbox"]:eq(' + (index + 1) + ")").prop("checked", true);
              $('div.layui-table-fixed input[name="layTableCheckbox"]:eq(' + (index + 1) + ")")
                .next()
                .addClass("layui-form-checked");
            }
          });
        }
        form.render("checkbox");
      }
    });

    // 工具条点击事件
    table.on("tool(productItemTable)", function (obj) {
      var data = obj.data;
      if (obj.event === "editItem") {
        //修改
        data.eventType = "editItem";
        showEditItemModel(data);
      } else if (obj.event === "del") {
        // 删除
        doDelete(obj);
      }
    });

    function doDelete(obj) {
      layer.confirm(
        "确定要删除吗？",
        {
          offset: "65px",
          skin: "layui-layer-admin"
        },
        function (i) {
          layer.close(i);
          layer.load(2);
          admin.req(
            "enterprise/product/admin/productItem/" + obj.data.id,
            {},
            function (res) {
              layer.closeAll("loading");
              if (res.code == 200) {
                layer.msg(res.msg, { icon: 1 });
                obj.del();
                table.reload("productItemTable");
              } else {
                layer.msg(res.msg, { icon: 2 }); // 缺失的右花括号和圆括号
              }
            },
            "DELETE"
          ); // 缺失的圆括号
        }
      );
    }

    //监听排序
    table.on("sort(productItemTable)", function (obj) {
      table.reload("productItemTable", {
        initSort: obj,
        where: {
          sort: obj.field,
          order: obj.type
        }
      });
    });

    // 搜索
    form.on("submit(itemTableFormSubSearchLog)", function (data) {
      insTb.reload({ where: data.field, page: { curr: 1 } }, "data");
    });

    form.on("switch(isDeleted)", function (obj) {
      if (obj.elem.checked) {
        enable(obj.value);
      } else {
        disable(obj.value);
      }
    });

    function enable(id) {
      admin.req(
        "enterprise/product/admin/productAttribute/enable",
        { id: id },
        function (res) {
          if (res.code == 200) {
            layer.msg(res.msg, { icon: 1 });
            table.reload("productAttrTable");
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        "GET"
      );
    }

    function disable(id) {
      admin.req(
        "enterprise/product/admin/productAttribute/disable",
        { id: id },
        function (res) {
          if (res.code == 200) {
            layer.msg(res.msg, { icon: 1 });
            table.reload("productAttrTable");
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        "GET"
      );
    }

    // 添加按钮点击事件
    $("#productItemBtnAdd").click(function () {
      data.eventType = "addItemFromAttrTable";
      showEditItemModel(data);
    });

    $("#productItemCategoryBtnAdd").click(function () {
      data.eventType = "addItemFromAttrTable";
      showEditItemCategoryModel(data, undefined, "productItemCategoryForm", "productItemCategoryFormSubmit");
    });

    $("#productAttrBtnDel").click(function () {
      var checkRows = table.checkStatus("productAttrTable");
      if (checkRows.data.length == 0) {
        layer.msg("请选择要删除的数据", { icon: 2 });
      } else {
        var ids = "";
        checkRows.data.forEach((item) => {
          ids += item.id + ",";
        });
        delBatch(ids);
      }
    });

    function delBatch(ids) {
      admin.req(
        "enterprise/product/admin/productAttribute/delBatch",
        { ids: ids },
        function (res) {
          if (res.code == 200) {
            layer.msg(res.msg, { icon: 1 });
            table.reload("productAttrTable");
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        "POST"
      );
    }

    window.addEventListener("load", () => {
      console.log(123, $(".layui-layer-content"));
    });

    function showEditItemModel(data) {
      var openIndex = admin.open({
        type: 1,
        area: "840px",
        offset: "150px",
        title: data && (data.eventType == "addItem" || data.eventType == "addItemFromAttrTable") ? "添加物资检测项目" : "修改物资检测项目",
        content: $("#productItemForm").html(),
        success: function () {
          //初始化物资分类
          admin.initDataSelect(
            "enterprise/product/admin/productType/list",
            { limit: 9999 },
            "productType",
            data.productType != null ? data.productType : data.id,
            "物资分类",
            null,
            null
          );
          //初始化物资性质
          admin.getDictList("productNature", "sys_product_type_nature", data.productNature != null ? data.productNature : data.materialNature, "物资性质");
          //初始化检测类型
          admin.getDictList("itemType", "sys_product_item_type", data.itemType, "业务类型");
          //初始化检测业务分类
          admin.initDataSelect("production/qualityTesting/admin/qualityTestingCategory/list", { limit: 9999 }, "qualityTestingCategoryId", data.qualityTestingCategoryId, "检测业务分类", null, null);
          //初始化检测业务类型
          admin.initDataSelect("production/qualityTesting/admin/qualityTestingType/list", { limit: 9999 }, "qualityTestingTypeId", data.qualityTestingTypeId, "检测业务类型", null, null);
          //初始化检测项目分类
          admin.initDataSelect("enterprise/product/admin/productItemCategory/list", { limit: 9999 }, "itemCategoryId", data.itemCategoryId, "检测项目分类", null, null);
          //初始化样式
          admin.getDictList("testMethod", "sys_detection_method", data.style, "检测方法");
          //初始化样式
          admin.getDictList("style", "sys_product_item_style", data.style, "检测样式");

          if (data && data.eventType != "addItem" && data.eventType != "addItemFromAttrTable") {
            form.val("productItemForm", data);
          }

          var getTemplateHtml = function (i) {
            var labelName = "";
            var valLen = $("form input[name='value']").length;
            var classNew = "";
            if (valLen == 0) {
              labelName = "属性值";
            } else {
              classNew = "newAdd";
            }
            var templateHtml =
              "" +
              '<div class="attributeDiv layui-form-item ' +
              classNew +
              '" >' +
              '<div class="layui-form-item">' +
              "<div >" +
              '<label class="layui-form-label" >' +
              labelName +
              "</label>" +
              '<div class="layui-input-inline">' +
              '<input id="value' +
              i +
              '" name="value" placeholder="请输入属性" type="text" class="layui-input" lay-verify="required" required/>' +
              "</div>" +
              "</div>" +
              "<div >" +
              "</div>";
            templateHtml +=
              '<div class="layui-input-inline">' +
              '<button id="btnDel' +
              i +
              '" class="layui-btn delBtn" lay-filter="btnDel' +
              i +
              '" style="margin-left: 20px;">删除</button>' +
              "</div>";
            templateHtml += "</div>" + "</div>";
            return templateHtml;
          };

          var addTemplateDiv = function () {
            var html = getTemplateHtml(i++);
            $("#btnAddDiv2").prev().after(html);
            form.render();
            form.render("select");
            $(".delBtn")
              .off("click")
              .on("click", function () {
                var btn = $(this);
                var btnId = btn[0].id;
                var btnNo = btnId.substring("btnDel".length, btnId.length);
                btn.parent().parent().parent().remove();
              });
          };

          $("#btnAdd").click(addTemplateDiv);
          if (data && (data.eventType == "addItem" || data.eventType == "addItemFromAttrTable")) {
            $("#btnAdd").hide();
          }

          form.on("select(style)", function (data) {
            if (data.value == "text") {
              $("#btnAdd").hide();
              $(".attributeDiv").remove();
            } else if (data.value == "single") {
              $("#btnAdd").show();
              if ($("form input[name='value']").length == 0) {
                addTemplateDiv();
                $("#btnDel0").hide();
              }
            }
          });

          // 表单提交事件
          form.on("submit(productItemFormSubmit)", function (d) {
            layer.load(2);
            var isDeleted = $("form input[name='isDeleted']").prop("checked");
            if (!isDeleted) {
              d.field.isDeleted = false;
            } else {
              d.field.isDeleted = true;
            }
            admin.req(
              data && (data.eventType == "addItem" || data.eventType == "addItemFromAttrTable")
                ? "enterprise/product/admin/productItem/add"
                : "enterprise/product/admin/productItem/update",
              JSON.stringify(d.field),
              function (res) {
                layer.closeAll("loading");
                if (res.code == 200) {
                  layer.msg(res.msg, { icon: 1 });
                  if (data && (data.eventType == "addItemFromAttrTable" || data.eventType == "editItem")) {
                    table.reload("productItemTable");
                    layer.close(openIndex);
                  } else {
                    layer.closeAll("page");
                  }
                } else {
                  layer.msg(res.msg, { icon: 2 });
                }
              },
              "POST",
              true,
              "application/json; charset=utf-8"
            );
            return false;
          });
        }
      });
    }

    function showEditItemCategoryModel(productTypeData, data, formId, submitButton, parentIdVal) {
      var openIndex = admin.open({
        type: 1,
        area: "540px",
        offset: "150px",
        title: "添加检测项目分类",
        content: $("#productItemCategoryForm").html(),
        success: function () {
          //初始化物资分类
          admin.initDataSelectTree(
            true,
            "enterprise/product/admin/productType/getTreeData",
            { limit: 9999 },
            "selectProductTypeQuery",
            productTypeData.id,
            "物资分类",
            "productType",
            null
          );
          //初始化物资性质
          admin.getDictList("productNature", "sys_product_type_nature", productTypeData.materialNature, "物资性质");
          //初始化检测类型
          admin.getDictList("itemType", "sys_product_item_type", null, "检测类型");

          // 表单提交事件
          form.on("submit(" + submitButton + ")", function (d) {
            layer.load(2);
            var isDeleted = $("form input[name='isDeleted']").prop("checked");
            if (!isDeleted) {
              d.field.isDeleted = false;
            } else {
              d.field.isDeleted = true;
            }
            d.field.productType = productTypeData.id;
            admin.req(
              data ? "enterprise/product/admin/productItemCategory/update" : "enterprise/product/admin/productItemCategory/add",
              d.field,
              function (res) {
                layer.closeAll("loading");
                if (res.code == 200) {
                  layer.msg(res.msg, { icon: 1 });
                  layer.close(openIndex);
                } else {
                  layer.msg(res.msg, { icon: 2 });
                }
              },
              data ? "PUT" : "POST"
            );
            return false;
          });
        }
      });
    }
  });
</script>
